//
//  QZHomeRankVC.m
//  shortvideoplay
//
//  Created by tikeios_002 on 2024/6/24.
//

#import "QZHomeRankVC.h"
#import "QZHomePlayCell.h"
#import "QZVideoModel.h"
#import "BVideoCacheTool.h"
#import "JPVideoPlayerKit.h"
#import "AVPlayerManager.h"
#import "QZCommentVC.h"
#import "CSJADLoading.h"
#import "QZHomePopularVC.h"
#import "GDTNativeExpressAdView.h"
#import "PublicView.h"

@interface QZHomeRankVC ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong,nonatomic) UICollectionView * videoCollection;
@property (assign ,nonatomic) int requestPage;
@property (strong ,nonatomic) NSString * videoAllIds;
@property (strong,nonatomic) NSMutableArray <QZVideoModel *>* videoArr;

@property (strong ,nonatomic) QZHomePlayCell *videoPlayCell;
@property (assign ,nonatomic) NSInteger videoPlayIndex;
@property (assign ,nonatomic) CGFloat videoCellHeight;
@property (assign ,nonatomic) BOOL isChangeVideo;//是否切换视频
@property (assign, nonatomic) NSInteger adRow;
@property (assign, nonatomic) NSInteger adNowRow;
@property (assign ,nonatomic) BOOL isRequestNow;
@property (assign ,nonatomic) BOOL isAddVideo;
@property (nonatomic, assign) BOOL  isPresentCommen;
@property (nonatomic, assign) BOOL  isZaiNowView;
@property (nonatomic, strong) PublicView * nullView;
@property (nonatomic, strong) NSMutableArray * blockIdArr;
@end

@implementation QZHomeRankVC
- (NSMutableArray *)sourceData{
    return self.videoArr;
}
- (void)updateData:(QZVideoModel *)data index:(NSInteger)index type:(QZDataUpdateType)type{
    if(type == QZDataUpdateLike){
        [_videoPlayCell uploadShowPlayModel:data];
    }else if (type == QZDataUpdateCollect){
        [_videoPlayCell uploadShowPlayModel:data];
    }else if (type == QZDataUpdateFollow){
        [_videoPlayCell uploadShowPlayModel:data];
    }else if (type == QZDataUpdateNoLike){
        [self.videoArr removeObjectAtIndex:index];
        [_videoCollection reloadData];
        if(self.videoPlayIndex >= self.videoArr.count){
            [self playToLast];
        }else{
            self.videoPlayIndex = self.videoPlayIndex;
        }
    }
}
- (void)delData:(QZVideoModel *)data index:(NSInteger)index type:(QZDataUpdateType)type{
    if (type == QZDataUpdateNoLike){
        [self.videoArr removeObjectAtIndex:index];
        [_videoCollection reloadData];
        if(self.videoPlayIndex >= self.videoArr.count){
            [self playToLast];
        }else{
            self.videoPlayIndex = self.videoPlayIndex;
        }
    }
}
- (void)delObjWithId:(id)delId type:(QZDataUpdateType)type{
    if (type == QZDataUpdateBlock){
        if(![self.blockIdArr containsObject:delId]){
            [self.blockIdArr addObject:delId];
        }
    }else if (type == QZDataUpdateCancelBlock){
        if([self.blockIdArr containsObject:delId]){
            [self.blockIdArr removeObject:delId];
        }
    }
}
- (void)playToLast{
    self.videoCollection.panGestureRecognizer.enabled = NO;
    KWeakSelf
    [UIView animateWithDuration:0.15
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseOut animations:^{
        //UITableView滑动到指定cell
        [weakSelf.videoCollection scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.videoArr.count-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        weakSelf.videoPlayIndex = weakSelf.videoArr.count-1;
        
        weakSelf.requestPage++;
        weakSelf.isAddVideo = YES;
        [weakSelf getRecommendVideos];
        
    } completion:^(BOOL finished) {
        //UITableView可以响应其他滑动手势
        weakSelf.videoCollection.panGestureRecognizer.enabled = YES;
    }];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if(self.blockIdArr.count > 0){
        BOOL isExit = NO;
        NSMutableArray * sum = [NSMutableArray new];
        for (QZVideoModel * model in self.videoArr) {
            if([self.blockIdArr containsObject:model.mid]){
                isExit = YES;
            }else{
                [sum addObject:model];
            }
        }
        if (isExit) {
            [self.videoCollection reloadData];
            self.videoArr = [sum mutableCopy];
            if(self.videoPlayIndex >= self.videoArr.count){
                [self playToLast];
            }else{
                self.videoPlayIndex = self.videoPlayIndex;
            }
            
            
            self.isZaiNowView = YES;
            [QZUserInfoModel share].mainVC = self;
            [self.blockIdArr removeAllObjects];
            [sum removeAllObjects];
            return;
        }else{
            [self.blockIdArr removeAllObjects];
            [sum removeAllObjects];
        }
    }
    
    if(self.videoArr.count > 0 && self.videoArr[_videoPlayIndex].is_ADView == NO){
        if([QZHongBaoView share].hidden){
            [QZHongBaoView share].hidden = NO;
        }
        [_videoPlayCell video_playTap];
    }
    self.isZaiNowView = YES;
    [QZUserInfoModel share].mainVC = self;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if(self.isPresentCommen == NO){
        if(self.videoArr.count > 0 && self.videoArr[_videoPlayIndex].is_ADView == NO && _videoPlayCell != nil){
            [QZHongBaoView share].hidden = YES;
            [[QZHongBaoView share] stopClick:NO];
            [_videoPlayCell video_pauseTap];
        }
        _isZaiNowView = NO;
    }
}
-(void)showTextViewNavViewTo1{
    NSMutableArray * showTextViewNavViewNameArrTo1 = [NSMutableArray new];
    UIView * showTextViewNavViewViewTo1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    showTextViewNavViewViewTo1.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:showTextViewNavViewViewTo1];
    UILabel * showTextViewNavViewLabelTo1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    NSInteger showTextViewNavViewNumberTo1 = arc4random_uniform(20);
    NSLog(@"：%ld", (long)showTextViewNavViewNumberTo1);
    showTextViewNavViewLabelTo1.text = [NSString stringWithFormat:@"%ld",(long)showTextViewNavViewNumberTo1];
    [showTextViewNavViewLabelTo1 addSubview:showTextViewNavViewLabelTo1];
    
    UIImageView * showTextViewNavViewLabelTo2 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [showTextViewNavViewViewTo1 addSubview:showTextViewNavViewLabelTo2];
    
}
- (void)showOldAddNavViewToMainOldView1{
    UIView * oldBgSS = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    oldBgSS.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:oldBgSS];
    
    UIButton * sendBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreen_W-75, kStatusBarHeight+10, 60, 46)];
    sendBtn.layer.cornerRadius = 3;
    sendBtn.backgroundColor = [UIColor whiteColor];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:ColorHex(@"#333333") forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [sendBtn addTarget:self action:@selector(sendTap) forControlEvents:UIControlEventTouchUpInside];
    [oldBgSS addSubview:sendBtn];
    
    UIView * sendBg = [[UIView alloc]initWithFrame:CGRectMake(15, kStatusBarHeight+66, KScreen_W-30, (KScreen_H-KSafeAreaBottomHeight-25-(kStatusBarHeight+66))/2)];
    sendBg.backgroundColor = [UIColor whiteColor];
    sendBg.layer.cornerRadius = 3;
    [oldBgSS addSubview:sendBg];
    
    UILabel * sendTip = [[UILabel alloc]initWithFrame:CGRectMake(0, (sendBg.frame.size.height-40)/2, sendBg.frame.size.width, 40)];
    sendTip.text = @"发送区";
    sendTip.textColor = ColorHex(@"#f0f0f0");
    sendTip.textAlignment = NSTextAlignmentCenter;
    sendTip.font = [UIFont systemFontOfSize:28];
    [sendBg addSubview:sendTip];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.videoAllIds = @"";
    self.adRow = 2;
    _videoCellHeight = KScreen_H-KTab_H;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 0.0;
    flowLayout.minimumInteritemSpacing = 0.0;
    flowLayout.footerReferenceSize = CGSizeZero;
    flowLayout.headerReferenceSize = CGSizeZero;
    flowLayout.sectionInset = UIEdgeInsetsZero;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    flowLayout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    //创建collectionView 通过一个布局策略layout来创建
    self.videoCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, KScreen_W, KScreen_H-KTab_H) collectionViewLayout:flowLayout];
    self.videoCollection.backgroundColor = viewback_black;
    if (@available(iOS 11.0, *)) {
        self.videoCollection.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    //代理设置
    self.videoCollection.scrollsToTop = NO;
    self.videoCollection.delegate=self;
    self.videoCollection.dataSource=self;
    self.videoCollection.pagingEnabled = YES;
    self.videoCollection.showsVerticalScrollIndicator = NO;
    self.videoCollection.showsHorizontalScrollIndicator = NO;
    //注册item类型 这里使用系统的类型
    [self.videoCollection registerClass:[QZHomePlayCell class] forCellWithReuseIdentifier:@"playcell"];
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:self.videoCollection];
    KWeakSelf
    //    self.videoCollection.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
    //        //下拉刷新要做的操作.
    //        NSLog(@"下拉");
    //        weakSelf.videoCollection.userInteractionEnabled = NO;
    //        weakSelf.requestPage = 0;
    //        [weakSelf getRecommendVideos];
    //    }];
//    self.videoCollection.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//        //下拉刷新要做的操作.
//        weakSelf.requestPage = weakSelf.requestPage+1;
//        [weakSelf getRecommendVideos];
//    }];
    [self.videoCollection.mj_header endRefreshing];
    [self.videoCollection.mj_footer endRefreshing];
    [SVProgressHUDTool showWithStatus:nil];
    [self getRecommendVideos];
    [[QZDataUpdate share] addListenerObj:self];
    // 进入后台
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appHasGoneInBackground)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    // 回到程序
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appHasGoneInForeground)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabbarDoubleClick) name:@"tabbarRefishData" object:nil];
}
- (void)appHasGoneInBackground{
    //进入后台
    NSLog(@"111");
    
}
- (void)appHasGoneInForeground{
    // 回到程序
    NSLog(@"222");
    if(self.isZaiNowView && self.videoArr.count > 0 && self.videoArr[_videoPlayIndex].is_ADView == NO){
        if(_videoPlayCell.isPlayerReady){
            [_videoPlayCell video_playTap];
        }
    }
}
#pragma mark 刷新

- (NSMutableArray *)videoArr{
    if(_videoArr == nil){
        _videoArr = [NSMutableArray new];
    }
    return _videoArr;
}
- (NSMutableArray *)blockIdArr{
    if(_blockIdArr == nil){
        _blockIdArr = [NSMutableArray new];
    }
    return _blockIdArr;
}
- (void)tabbarDoubleClick {
    if(self.isZaiNowView){
        [SVProgressHUDTool showWithStatus:nil];
        self.requestPage = 0;
        [self getRecommendVideos];
    }
}
-(void)getRecommendVideos{
    _isRequestNow = YES;
    KMutableDic(sendDic)
    if(self.videoAllIds.length > 0){
        sendDic[@"videoids"] = [self.videoAllIds substringWithRange:NSMakeRange(0, self.videoAllIds.length-1)];
    }
    KWeakSelf
    [YBNetBase tikeRankRequest:sendDic successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
        [SVProgressHUDTool dismiss];
        [weakSelf.videoCollection.mj_header endRefreshing];
        [weakSelf.videoCollection.mj_footer endRefreshing];
        weakSelf.videoCollection.userInteractionEnabled = YES;
        //        if(code == 200){
        //            for (int i =0; i<[data[@"ranks"] count]; i++) {
        //                QZVideoModel * model = [[QZVideoModel alloc]init];
        //                [model setValuesForKeysWithDictionary:data[@"ranks"][i]];
        //                if(weakSelf.videoArr.count == weakSelf.adRow){
        //                    QZVideoModel * admodel = [[QZVideoModel alloc]init];
        //                    admodel.is_ADView = YES;
        //                    [weakSelf.videoArr addObject:admodel];
        //                    weakSelf.adRow = weakSelf.adRow+7;
        //                }
        //                [weakSelf.videoArr addObject:model];
        //                weakSelf.videoAllIds = [NSString stringWithFormat:@"%@%@,",weakSelf.videoAllIds,model.videoid];
        //            }
        //            [weakSelf requestEnd];
        //        }else{
        //            [YBMsgPop showPop:msg];
        //        }
        //        weakSelf.isRequestNow = NO;
        if(code == 200){
            weakSelf.adNowRow = weakSelf.adRow;
            int number = 0;
            for (int i =0; i<[data[@"ranks"] count]; i++) {
                if(![data[@"ranks"][i][@"member"][@"video"][@"video_url"] isKindOfClass:[NSDictionary class]] || data[@"ranks"][i][@"member"][@"video"][@"video_url"] == nil  || [data[@"ranks"][i][@"member"][@"video"][@"video_url"] allKeys].count == 0){
                    continue;
                }
                QZVideoModel * model = [[QZVideoModel alloc]init];
                [model setValuesForKeysWithDictionary:data[@"ranks"][i][@"member"][@"video"]];
                model.income = [NSString stringWithFormat:@"%@元",data[@"ranks"][i][@"member"][@"income"]];
                model.is_rank = YES;
                if(weakSelf.videoArr.count == weakSelf.adRow){
                    QZVideoModel * admodel = [[QZVideoModel alloc]init];
                    admodel.is_ADView = YES;
                    [weakSelf.videoArr addObject:admodel];
                    weakSelf.adRow = weakSelf.adRow+7;
                    number++;
                }
                [weakSelf.videoArr addObject:model];
                weakSelf.videoAllIds = [NSString stringWithFormat:@"%@%@,",weakSelf.videoAllIds,model.videoid];
            }
            if(number == 0){
                [SVProgressHUDTool dismiss];
                [weakSelf requestEnd];
            }else{
                [weakSelf addAdRequest:number];
            }
            
            
        }else{
            [YBMsgPop showPop:msg];
        }
        weakSelf.isRequestNow = NO;
    }];
}
- (void)addAdRequest:(NSInteger)number{
    KWeakSelf
    [CSJADLoading share].ADNativeAdsLoadFish = ^(NSArray * _Nullable nativeAdDataArray, NSInteger type) {
        if(nativeAdDataArray == nil){
            [SVProgressHUDTool dismiss];
            [weakSelf requestEnd];
        }else{
            
            [nativeAdDataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                if(type == 0){
                    BUNativeExpressAdView *expressView = (BUNativeExpressAdView *)obj;
                    expressView.rootViewController = weakSelf;
                    // important: 此处会进行WKWebview的渲染，建议一次最多预加载三个广告，如果超过3个会很大概率导致WKWebview渲染失败。
                    [expressView render];
                    weakSelf.videoArr[weakSelf.adNowRow].expressView = expressView;
                }else{
                    GDTNativeExpressAdView *expressView = (GDTNativeExpressAdView *)obj;
                    expressView.controller = weakSelf;
                    // important: 此处会进行WKWebview的渲染，建议一次最多预加载三个广告，如果超过3个会很大概率导致WKWebview渲染失败。
                    [expressView render];
                    weakSelf.videoArr[weakSelf.adNowRow].expressView = expressView;
                }
                weakSelf.videoArr[weakSelf.adNowRow].expressViewId = [NSString stringWithFormat:@"%ld",[Tools shuijishu]];
                if(idx+1 == nativeAdDataArray.count){
                    [SVProgressHUDTool dismiss];
                    [weakSelf requestEnd];
                }else{
                    weakSelf.adNowRow = weakSelf.adNowRow+7;
                }
            }];
        }
    };
    [CSJADLoading ADNativeAdsAdRequest:number];
}
- (void)requestEnd{
    [self.videoCollection reloadData];
    if(self.requestPage == 0 && self.videoArr.count != 0){
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            self.videoCollection.contentOffset = CGPointZero;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self addObserver:self forKeyPath:@"videoPlayIndex" options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew context:nil];
            });
            
        });
        [QZHongBaoView share].hidden = NO;
        self.nullView.hidden = YES;
    }else{
        if(self.videoArr.count == 0){
            [QZHongBaoView share].hidden = YES;
            self.nullView.hidden = NO;
        }
    }
}
- (PublicView *)nullView{
    if(_nullView == nil){
        _nullView = [[PublicView alloc]initWithFrame:CGRectMake(0, (KScreen_H-KTab_H-200)/2, KScreen_W, 200)];
        _nullView.publicLabel.text = @"还没有排行作品哦~";
        _nullView.hidden = YES;
        _nullView.userInteractionEnabled = NO;
           UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:_nullView];
    }
    return _nullView;
}
#pragma mark 代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.videoArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if(self.isAddVideo && self.videoPlayCell != nil && indexPath.row == self.videoPlayIndex){
        return self.videoPlayCell;
    }
    QZHomePlayCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"playcell" forIndexPath:indexPath];
    cell.videoModel = _videoArr[indexPath.row];
    cell.indexRow = indexPath.row;
    
    if(_videoArr[indexPath.row].is_ADView == NO){
//        [cell startDownloadBackgroundTask];
        KWeakSelf
        cell.myPlayCommentBlock = ^(NSInteger index) {
            [weakSelf commenView];
        };
        cell.myPlayPopularBlock = ^(NSString * _Nonnull popular) {
            [QZHongBaoView share].hidden = YES;
            [[QZHongBaoView share] stopClick:NO];
            QZHomePopularVC * popularvc = [[QZHomePopularVC alloc]init];
            popularvc.popular = popular;
            [weakSelf.navigationController pushViewController:popularvc animated:YES];
        };
    }
    //    if(_videoArr[indexPath.row].is_ADView && _videoArr[indexPath.row].expressView == nil){
    //        KWeakSelf
    //        [CSJADLoading share].ADNativeAdsLoadFish = ^(NSArray * _Nullable nativeAdDataArray, NSInteger type) {
    //            [nativeAdDataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    //                BUNativeExpressAdView *expressView = (BUNativeExpressAdView *)obj;
    //                expressView.rootViewController = self;
    //                // important: 此处会进行WKWebview的渲染，建议一次最多预加载三个广告，如果超过3个会很大概率导致WKWebview渲染失败。
    //                [expressView render];
    //                weakSelf.videoArr[indexPath.row].expressView = expressView;
    //                BUNativeExpressAdView *view = weakSelf.videoArr[indexPath.row].expressView;
    //                view.tag = 1000;
    //                [cell.ADPlayView addSubview:view];
    //    
    //            }];
    //            
    //        };
    //        [CSJADLoading ADNativeAdsAdRequest:1];
    //    }
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(KScreen_W, _videoCellHeight);
}
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_videoPlayCell == cell) {
        _isChangeVideo = YES;
    }else{
        _isChangeVideo = NO;
    }
}
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    
}

#pragma ScrollView delegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    dispatch_async(dispatch_get_main_queue(), ^{
        CGPoint translatedPoint = [scrollView.panGestureRecognizer translationInView:scrollView];
        //UITableView禁止响应其他滑动手势
        scrollView.panGestureRecognizer.enabled = NO;
        
        if(translatedPoint.y < -50 && self.videoPlayIndex < (self.videoArr.count - 1)) {
            if(self.videoArr[self.videoPlayIndex+1].is_ADView && self.videoArr[self.videoPlayIndex+1].expressView == nil){
                self.videoPlayIndex = self.videoPlayIndex+2;
            }else{
                self.videoPlayIndex ++;
            }
            //向下滑动索引递增
        }
        if(translatedPoint.y > 50 && self.videoPlayIndex > 0) {
            if(self.videoArr[self.videoPlayIndex-1].is_ADView && self.videoArr[self.videoPlayIndex-1].expressView == nil){
                self.videoPlayIndex = self.videoPlayIndex-2;
            }else{
                self.videoPlayIndex --;
            }
            //向上滑动索引递减
        }
        [UIView animateWithDuration:0.15
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseOut animations:^{
            //UITableView滑动到指定cell
            [self.videoCollection scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.videoPlayIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        } completion:^(BOOL finished) {
            //UITableView可以响应其他滑动手势
            scrollView.panGestureRecognizer.enabled = YES;
        }];
    });
}
#pragma KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    //观察currentIndex变化
    if ([keyPath isEqualToString:@"videoPlayIndex"]) {
        KWeakSelf
        //执行延迟函数
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 需要延迟执行的代码
        if(weakSelf.videoPlayIndex == weakSelf.videoArr.count-5){
            weakSelf.requestPage++;
            weakSelf.isAddVideo = YES;
            [weakSelf getRecommendVideos];
        }
        //设置用于标记当前视频是否播放的BOOL值为NO
        if(_videoPlayCell != nil && weakSelf.videoArr[_videoPlayCell.indexRow].is_ADView == NO){
            QZVideoModel * old = self.videoArr[_videoPlayCell.indexRow];
            old.play_durations = @([old.durations floatValue]*_videoPlayCell.sliderView.value);
            [QZUserInfoModel addHisPlay:old.videoid durations:[old.play_durations floatValue] isPlayEnd:NO];
        }
        [[QZHongBaoView share] stopClick:NO];
        //获取当前显示的cell
        if(weakSelf.videoArr[weakSelf.videoPlayIndex].is_ADView == YES){
            [weakSelf adVideoPlay];
            return;
        }
        if([QZUserInfoModel isLogin] && weakSelf.isZaiNowView){
            [QZHongBaoView share].hidden = NO;
        }
        [weakSelf.videoPlayCell video_pauseTap];
        //获取当前显示的cell
        if(weakSelf.videoArr[weakSelf.videoPlayIndex].is_ADView == YES){
            [self adVideoPlay];
        }else{
            if(weakSelf.videoArr[_videoPlayCell.indexRow].is_ADView){
                [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(adTimePlay) userInfo:nil repeats:NO];
            }
            weakSelf.videoPlayCell = (QZHomePlayCell *)[weakSelf.videoCollection cellForItemAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.videoPlayIndex inSection:0]];
            if(weakSelf.videoArr[weakSelf.videoPlayIndex].video_play_url.length != 0){
                [_videoPlayCell video_playTap];
            }else{
                weakSelf.videoArr[weakSelf.videoPlayIndex].is_request_down = YES;
            }
        }
        
        [QZUserInfoModel addPlayNuber:self.videoArr[self.videoPlayIndex].videoid];
    } else {
        return [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
-(void)adTimePlay{
    [[QZHongBaoView share] stopClick:YES];
}
- (void)adVideoPlay{
    KWeakSelf
    _videoPlayCell = (QZHomePlayCell *)[_videoCollection cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_videoPlayIndex inSection:0]];
    [CSJADLoading share].ADNativeAdsLoadPlayFish = ^(BOOL isFish) {
        weakSelf.videoCollection.panGestureRecognizer.enabled = NO;
        weakSelf.videoPlayIndex = self.videoPlayIndex+1;
        [UIView animateWithDuration:0.15
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseOut animations:^{
            //UITableView滑动到指定cell
            [weakSelf.videoCollection scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.videoPlayIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        } completion:^(BOOL finished) {
            //UITableView可以响应其他滑动手势
            weakSelf.videoCollection.panGestureRecognizer.enabled = YES;
        }];
    };


    
}
- (void)statusBarTouchBegin {
    _videoPlayIndex = 0;
}

- (void)applicationBecomeActive {
    if(_isZaiNowView) {
        [_videoPlayCell video_playTap];
    }
}

- (void)applicationEnterBackground {
    [_videoPlayCell video_pauseTap];
}
#pragma mark 评论
-(void)commenView{
    self.isPresentCommen = YES;
    
    QZCommentVC * vc = [[QZCommentVC alloc]init];
    vc.numberIndex = [self.videoArr[_videoPlayIndex].comment_num intValue];
    vc.mId = self.videoArr[_videoPlayIndex].mid;
    vc.videoId = self.videoArr[_videoPlayIndex].videoid;
    [self presentPanModal:vc];
    
    //    [self.videoPlayCell commentMoveStatus:0 close:NO];
    //    _videoPlayCell.frame = CGRectMake(0, 0, KScreen_W, (KScreen_H-KTab_H)*0.35);
    KWeakSelf
    __block QZCommentVC * commenvc = vc;
    vc.commentMoveStatusBlock = ^(CGFloat offset, BOOL close) {
        [weakSelf.videoPlayCell commentMoveStatus:offset close:close];
        if(close){
            weakSelf.isPresentCommen = NO;
            weakSelf.videoArr[weakSelf.videoPlayIndex].comment_num = @(commenvc.numberIndex);
            [weakSelf.videoPlayCell uploadShowPlayModel:weakSelf.videoArr[weakSelf.videoPlayIndex]];
        }
        vc.commentPushViewControlBlock = ^(BOOL isleave) {
            if(isleave){
                if(weakSelf.videoArr.count > 0 && weakSelf.videoArr[weakSelf.videoPlayIndex].is_ADView == NO){
                    [QZHongBaoView share].hidden = YES;
                    [[QZHongBaoView share] stopClick:NO];
                    [weakSelf.videoPlayCell video_pauseTap];
                }
            }else{
                if(weakSelf.videoArr.count > 0 && weakSelf.videoArr[weakSelf.videoPlayIndex].is_ADView == NO){
                    if(weakSelf.videoPlayCell.isPlayerReady){
                        [QZHongBaoView share].hidden = NO;
                        [[QZHongBaoView share] stopClick:YES];
                        [weakSelf.videoPlayCell video_playTap];
                    }
                }
            }
        };
//        if(!close){
//            weakSelf.videoPlayCell.frame = CGRectMake(0, 0, KScreen_W, (KScreen_H-KTab_H)*0.35+offset);
//        }
    };
}
#pragma load data
- (void)loadData:(NSInteger)pageIndex pageSize:(NSInteger)pageSize {
    
}
#pragma mark CategoryListContentViewDelegate
- (UIView *)listView {
    return self.view;
}
//-(void)CellClose{
//    if (_videoArr.count == 0) {
//        return;
//    }
//    if (self.videoPlayCell.isplay && self.videoPlayCell.isOnePlayFinish) {
////        [self playNotFinish];//标记没有看完
//    }
//    self.videoPlayCell.isplay = NO;
//    self.videoPlayCell.isPause = NO;
//    self.videoPlayCell.hoem_recommend_imageView.hidden = NO;
//    self.videoPlayCell.hoem_recommend_playbutton.hidden = YES;
//    [self.videoPlayCell stopPlayWithUrl:_videoArr[_videoPlayIndex].video_url];
//}
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//    if (self->_videoArr.count == 0) {
//        return ;
//    }
//    if (_isChangeVideo || _videoPlayCell == _videoCollection.visibleCells.lastObject){
////            //播放
//        if (_videoArr.count-1 == _videoPlayIndex) {
//            [YBMsgPop showPop:@"没有更多视频"];
//            return;
//        }
//    }else{
//        if (scrollView.contentOffset.y / _videoCellHeight == self->_videoArr.count -1) {
//            [YBMsgPop showPop:@"没有更多视频"];
//            return;
//        }
//    }
//
//    if (_videoPlayCell != nil) {
//        [self CellClose];
//    }
//    _videoPlayIndex = scrollView.contentOffset.y / _videoCellHeight;
//    _videoPlayCell = (QZHomePlayCell *)[_videoCollection cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_videoPlayIndex inSection:0]];
//
//    QZVideoModel * model = _videoArr[_videoPlayIndex];
//    [_videoPlayCell resumePlay:model.video_url];
//    if(_videoPlayIndex+1 < _videoArr.count){
//        [self NextToPlay:_videoPlayIndex+1];
//    }
//
//
//    if (_videoPlayIndex > _videoArr.count-3 && _isRequestNow == NO) {
//        self.requestPage = self.requestPage+1;
//        [self getRecommendVideos];
//    }
//}
//-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//    NSTimeInterval time = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
////    //判断当前点击时间与上次点击时间的时间间隔
////    if(time - scrollTime < 1) {
////        collect.scrollEnabled = NO;
////        [NSTimer scheduledTimerWithTimeInterval:0.7 target:self selector:@selector(collect_start) userInfo:nil repeats:NO];
////        [YBMsgPop showPop:NSLocalizedString(@"操作频率过快", nil)];
////        return;
////    }
////    scrollTime = time;
//}
//
//#pragma mark 预加载
//- (void)NextToPlay:(NSInteger)nextRow{
//    [[BVideoCacheTool tool] preloadLoadVideo:_videoArr[nextRow].video_url];
//}
//#pragma mark 首次播放
//-(void)oneLoadPlay{
//    _isChangeVideo = YES;
//    [self scrollViewDidEndDecelerating:_videoCollection];
//}
@end
